import React from 'react';
import style from './style.styl';
import Charts from '../plugins/Charts';
import ReviewHeader from '../../containers/review/new/tool/ReviewHeader'
import {chartSchedules, getchartSchedulesLine,fetchSourceUsersCharts} from '../../actions/conversation.action';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {Select} from 'sq-ui';
import cx from 'classnames'
import util from '../../util';
import ConverTable from '../../containers/conversation/plugins/ConverTable';
import ConverCell from '../../containers/conversation/plugins/ConverCell';
import {Avatar, Link} from 'sq-ui';

const periodMap = [30,90,180,365];
const minTImeUnitMap = ['日','周','半月','月']
const oneDay = 60 * 60 * 1000 * 24;
const pageSize = 10;
@connect(({conversation})=>({conversation}), dispatch => ({actions: bindActionCreators({fetchSourceUsersCharts,chartSchedules, getchartSchedulesLine}, dispatch)}))
class ConverChart extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'ConverChart';
    this.state = {
      chartSchedules: {},
      chartSchedulesLine: [],
      minTimeUnit: 1,
      period: 0,
    }
  }
  componentDidMount() {
    this.props.actions.chartSchedules(({data}) => {
      this.setState({
        chartSchedules: data,
      })
    });
    this.getChartLine();
    this.onFetchRecord();
  }
  getChartLine = () => {
    const {
      minTimeUnit,
      period,
    } = this.state;
    this.props.actions.getchartSchedulesLine({period:periodMap[period], minTimeUnit}, ({data}) => {
      if(minTimeUnit === this.state.minTimeUnit && period === this.state.period){
        this.setState({
          chartSchedulesLine: data.convrScheduleChartVOList || [],
        });
      }
    })
  }
  updateField = (key, value) => {
    this.setState({
      [key]: +value,
    }, this.getChartLine);
  }
  getTime = (timeStr, period) => {
    if(period === 0) return timeStr;
    else if(period === 3) return timeStr.replace(/(\d{4}-\d{2})-\d{2}/, '$1月');
    else if(period === 1) {
      const day = new Date(timeStr);
      const nextDay = new Date(day.getTime() + oneDay*7);
      return timeStr + '\n至 ' + util.dateFormat(nextDay, 'yyyy-MM-dd')
    }else if(period === 2) {
      const flag = timeStr.match(/(\d{4}-\d{2})-(\d{2})/);
      if(flag && flag.length >= 3){
        return flag[2] === '01' ? flag[1]+'月上半月' : flag[1]+'月下半月';
      }else return timeStr;
    } 
  }
  getPageNum = (props) => {
    const {
      pageNum = 1,
    } = props.location.query;
    return pageNum;
  }
  onFetchRecord = (pageNum) => {
    const pageNumber = pageNum || this.getPageNum(this.props);
   
    this.props.actions.fetchSourceUsersCharts({
      pageNumber: pageNumber,
      pageSize: pageSize
    }); 
    
  }
  render() {
    const {
      minTimeUnit
    } = this.state;
    const {
      sourceUsers
    } = this.props.conversation;
    const pageNumber = this.getPageNum(this.props);
    const recordsData = {
      pageNum: pageNumber,
      pageCount: 0,
      data: null,
    };
    if(sourceUsers[`page_${pageNumber}`]){
      const dataItem = sourceUsers[`page_${pageNumber}`];
      const {
        totalNumber = 0,
        convrSourceChartVOList = [],
      } = dataItem || {};
      recordsData.pageCount = Math.ceil(totalNumber/pageSize);
      recordsData.data = convrSourceChartVOList || [];
    }
    return (
      <div>
        <ReviewHeader title={'当面交谈看板'}/>
        <div className={style['bar']} style={{width: '735px'}}>
          <label>时间范围：</label>
          <Select
            className={style['priority-select']}
            style={{ width: '100px',display: 'inline-block' }}
            value={this.state.period}
            onChange={value => this.updateField('period', value)}
            list={[
              '最近30天',
              '最近60天',
              '最近180天',
              '最近365天',
            ]}
            activeItem={
              (v, i, active) => (
                <li
                  key={i}
                  data-value={i}
                >
                  <span>{v}</span>
                </li>
              )
            }
            item={
              (v, i, active) => (
                <li
                  key={i}
                  data-value={i}
                >
                  <span>{v}</span>
                </li>
              )
            }
          />
          <div className={style['right']} >
            <label>最小时间单位：</label>
            <div className={style['select-box']}>
            {
              minTImeUnitMap.map((v,i) => {
                return (
                  <div className={cx({
                    [style['select-item']]: true,
                    [style['select-active']]: i === this.state.minTimeUnit,
                  })} key={i} onClick={() => {if(i !== this.state.minTimeUnit) this.updateField('minTimeUnit', i)}}>{v}</div>
                );
              }) 
            }
            </div>
          </div>
        </div>
        <Charts 
          width={735}
          height={464}
          style={{marginRight:'25px',display:'inline-block'}}
          data={this.state.chartSchedulesLine}
          title={'全公司总次数时间维度统计'}
          type={'line'}
          series={[
            {
              name:'计划交谈次数',
              value: function(item){return (+item['planedTimes']).toFixed(2)},
            },{
              name:'实际交谈次数',
              value: function(item){return item['actualTimes']},
            }
          ]}
          tooltip={{
            trigger:'axis',
          }}
          xAxis={{
            type: 'category',
            boundaryGap : false,
            name: '时间',
            value: (item) => {return this.getTime(item['date'], minTimeUnit)}
          }}
          yAxis={{
            name: '交谈次数',
            type: 'value',
          }}
        />  
        <Charts 
          width={340}
          height={464}
          data={[this.state.chartSchedules]}
          title={'本月交谈'}
          style={{display:'inline-block'}}
          type={'bar'}
          series={[
            {
              name:'计划交谈次数',
              value: function(item){return item['planedTimes']},
            },{
              name:'实际交谈次数',
              value: function(item){return item['actualTimes']},
            }
          ]}
          tooltip={{
            trigger:'item',
          }}
          xAxis={{
            type: 'category',
            name: '分数',
            value: function (item) {return item[0]}
          }}
          yAxis={{
            name: '交谈次数',
            type: 'value',
          }}
          legend={{
            top: 400,
            left: 'center',
          }}
        />
        <div>
          <div className={style['title']}>
            交谈发起人
          </div>
          <ConverTable data={recordsData} fetchData={this.onPage} style={{boxShadow: 'none'}}>
            <ConverCell item={v => v.sourceUser} header={'发起人'}  render={v => {
              const item = v;
              return (
                <Link
                  to={``}
                >
                  <span className={style['user-span']}>
                    <Avatar
                      src={item.avatarUrl}
                      width={36}
                    />
                    <span>{item.fullName}</span>
                  </span>
                </Link>
              );
            }}/>
            <ConverCell item={v => v.convrTimesInThisMonth} header={'本月次数'} width={200} />
            <ConverCell item={v => v.convrTimesInThisQuarter} header={'本季度次数'} width={200} />
            <ConverCell item={v => v.totalCount} header={'总发起次数'} width={200} />
            <ConverCell item={v => v.lastDate} header={'上次交谈时间'} width={200} />
          </ConverTable>
        </div>
      </div>


    );
  } 
} 
 
export default ConverChart;
